<template>
  <div>
    <div style="width: 400px; margin: 150px auto;">
      <h1 style="text-align: center; margin-bottom: 30px">后台登录</h1>
      <el-form :model="user" :rules="rules" size="large" ref="ruleFormRef">
        <el-form-item prop="username">
          <el-input v-model="user.username" :prefix-icon="User"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="user.password" :prefix-icon="Lock" show-password/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%" @click="login">登录</el-button>
        </el-form-item>
      </el-form>

    </div>
  </div>
</template>

<script setup>
// import {resetRouter, setRoutes} from "@/router";
// import Identify from "@/components/Identify";
import jsCookie from 'js-cookie';
import {ref, reactive, getCurrentInstance} from 'vue'
import {User, Lock} from '@element-plus/icons-vue'
import {ElMessage, ElNotification} from "element-plus";
import request from "../request.js";
import router from "../router";
// export default {
//   name: "Login",
//   data(){
//     return{
//       ruleForm: {
//         username: '',
//         password: ''
//       },
//     }
//   }
// }


  const {proxy} = getCurrentInstance()
  const rules = reactive({
    username:[
      {required:true, message:'请输入用户名', trigger:'blur'}
    ],
    password:[
      {required:true, message:'请输入密码', trigger:'blur'}
    ]
  })

  // const msg = ref('葛佳强')
  // const changeMsg = (val) =>{
  //   msg.value = val //赋值
  // }
  const user =reactive({
    // name: '张三'
  })
  // const changeUser = (name) =>{
  //   user.name = name
  // }
  const login = () => {
    proxy.$refs.ruleFormRef.validate((valid) => {
      if(valid){
        //向后台发请求 http://localhost:9090
        //{code:" ", msg, data}
        request.post('/user/login', user).then(res => {
           console.log("hhhhh"+JSON.stringify(user.username));
          if(res.code === '200'){ //请求成功
            localStorage.setItem('username', JSON.stringify(user.username));
            localStorage.setItem('user', JSON.stringify(user))
            ElNotification({
              type:'success',
              message:'成功'
            })
            router.push("/")
          }else{ //请求失败
            ElMessage({
              type:'error',
              message: res.msg
            })
          }
        })
      }else{
        ElMessage({
          type:'error',
          message:'用户名或密码错误'
        })
      }
    })
  }

</script>